package com.jackrain.nea.service;

import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.core.schema.TriggerHolder;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.sys.Command;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class Handle {
    
    /**
     * Get jsonObj for com.jackrain.nea.core.event.DefaultWebEvent, and return com.jackrain.nea.core.util.Result.toJSONString()
     *
     * @return should be com.jackrain.nea.core.util.Result.toJSONString()
     * @throws Exception
     */
    public static ValueHolder process(JSONObject jo, QuerySession qsession, DefaultWebEvent event, String Action) throws Exception {
        
        
        String cmd = null;
        TriggerHolder.VersionedTrigger trigger = null;
        Table table = null;

        RuntimeCompute runtimeCompute=ApplicationContextHandle.getBean("runtimeCompute");

        runtimeCompute.startRuntime();
                
        if (event.getParameterValue("command") != null) {
            cmd = (String) event.getParameterValue("command");
            TriggerHolder th = new TriggerHolder();
            trigger=th.parseTrigger(cmd);

        } else {

            TableManager tm = qsession.getTableManager();

           

            int tableid = jo.getIntValue("tableid");

            if (tableid > 0 && table == null) {
                table = tm.getTable(tableid);
            }

            if (jo.getString("table") != null && table == null) {
                table = tm.getTable(jo.getString("table"));
            }

            log.debug("handel jo->"+jo.toJSONString());
            
            log.debug("handel table->"+table.getName());
            
            trigger = table.getTrigger(Action);

        }
        try {
            log.debug("trigger ->" + trigger.toJSONObject());
        }catch (Exception e){
            throw  new NDSException(table+"当前表未配置EDAS服务程序，或者没有重载元数据请检查！");
        }

        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), trigger.getName(), trigger.getGroup(), trigger.getVersion());

        qsession.setEvent(event);

//        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.api.CbrandDelCmd", "ps", "1.0");

        ValueHolder result = ((Command) o).execute(qsession);

        Double spendTime=runtimeCompute.endRuntime();
        result.put("spendtime",spendTime);
        //ValueHolder result = (ValueHolder) ((CbrandDelCmd) o).execute(qsession);

        return result;

    }


}
